package nl.mad.drib.feeder;

import static java.lang.String.format;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import nl.mad.exceltestdata.ExcelTestData;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
 * Excel driven database feeder. Retrieves content from an excel
 * file and then inserts them into the database.
 * @author Jeroen van Schagen
 * @since 05-05-2011
 */
public class ExcelDatabaseFeeder extends SpringDatabaseFeeder {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelDatabaseFeeder.class);

    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    private String excelLocation = "classpath:import.xls";
    private boolean failOnExcelNotFound = true;

    private ExcelTestData excelTestData;

    /**
     * {@inheritDoc}
     */
    @Override
    public void perform() {
        InputStream excelInputStream = null;
        try {
            excelInputStream = createExcelInputStream();
            LOGGER.info("Import excel data: {}", excelLocation);
            excelTestData.persistData(excelInputStream);
        } catch (FileNotFoundException e) {
            if (failOnExcelNotFound) {
                throw new RuntimeException(e);
            } else {
                LOGGER.warn("Excel file '{}' could not be found.", excelLocation);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(excelInputStream);
        }
    }

    /**
     * Create a new input stream to our excel file.
     * @return input stream to the desired excel file
     * @throws FileNotFoundException whenever the file was not found
     * @throws IOException whenever the reader could not be opened
     */
    private InputStream createExcelInputStream() throws IOException {
        Resource resource = resourceLoader.getResource(excelLocation);
        if (!resource.exists()) {
            throw new FileNotFoundException(format("Excel file '%s' could not be found.", excelLocation));
        }
        return resource.getInputStream();
    }

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Required
    public void setExcelLocation(String excelLocation) {
        this.excelLocation = excelLocation;
    }

    public void setFailOnExcelNotFound(boolean failOnExcelNotFound) {
        this.failOnExcelNotFound = failOnExcelNotFound;
    }

    @Required
    public void setExcelTestData(ExcelTestData excelTestData) {
        this.excelTestData = excelTestData;
    }

}
